package com.salon.client.widgets.panels;

import java.util.ArrayList;
import java.util.List;

import org.apache.tools.ant.taskdefs.Sleep;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridSelectionModel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.menu.SeparatorMenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.PopupPanel;
import com.salon.client.GreetingServiceAsync;
import com.salon.client.Salon;
import com.salon.client.beans.IncomeMaterialsBean;
import com.salon.client.beans.ParentPagingLoadResult;
import com.salon.client.beans.PriceBean;
import com.salon.client.beans.WhereBean;
import com.salon.client.tabItems.IncomeTabItemPanel;
import com.salon.client.tabItems.PriceTabItemPanel;
import com.salon.client.widgets.PriceDialog;

public class PriceProcedurePanel extends ContentPanel{
	private ContentPanel pricePanel = new ContentPanel();
	private ContentPanel priceMaterPanel = new ContentPanel();
	
	
	protected ListStore<BeanModel> store = new ListStore<BeanModel>();
	protected ListStore<BeanModel> matStore = new ListStore<BeanModel>();
	//protected List<PriceBean> prices = null;
	
	protected ToolBar toolbar = new ToolBar();
	protected Grid<BeanModel> grid;
	protected Grid<BeanModel> matGrid;
	private BeanModel selectedPriceBean = null;
	private BeanModel selectedMaterial = null;
	//public List<WhereBean> wheres = new ArrayList<WhereBean>();
	private static BeanModelFactory materialFactory = null;
	private static BeanModelFactory priceFactory = null;
	private ProcedurePanel parent = null;
	
	static {
		try {
			materialFactory = BeanModelLookup.get().getFactory(IncomeMaterialsBean.class);
			priceFactory = BeanModelLookup.get().getFactory(PriceBean.class);
		}
		catch (Exception e) {}
	}
	
	public void setParent(ProcedurePanel parent) {
		this.parent = parent;
	}
	
	public PriceProcedurePanel() {
		setBodyBorder(false);
		setHeaderVisible(false);
		setButtonAlign(HorizontalAlignment.CENTER);
		setHeight(300);
		setWidth(600);
		RowLayout r = new RowLayout();
		r.setOrientation(Style.Orientation.HORIZONTAL);
		setLayout(r);
		
		pricePanel.setBodyBorder(false);
		pricePanel.setHeading("Услуги");
		pricePanel.setLayout(new FitLayout());
		
		priceMaterPanel.setBodyBorder(false);
		priceMaterPanel.setHeading("Калькуляция");
		priceMaterPanel.setLayout(new FitLayout());
		
		toolbar.setBorders(true);
		setBottomComponent(toolbar);
		
		initComponents();
		
	}
	
	protected void initComponents() {		
		addButton("Удалить услугу", "brit-delete-user", new SelectionListener<ButtonEvent>() {
			
			public void componentSelected(ButtonEvent ce) {
				if (selectedPriceBean != null) {
					store.remove(selectedPriceBean);
					parent.recalcCost();
					Info.display("Удаление услуги", "успешно");
				}
			}
		});
		
		addButton("Добавить расходник", "brit-add-user", new SelectionListener<ButtonEvent>() {
			
			public void componentSelected(ButtonEvent ce) {
				if (selectedPriceBean == null) {
					Info.display("Выберите ", "услугу");
					return;
				}
				PopupPanel dlg = new PopupPanel();
				dlg.setAnimationEnabled(true);
				dlg.setSize("500px", "300px");
				UsedMaterialForProcedurePanel panel = new UsedMaterialForProcedurePanel(PriceProcedurePanel.this, dlg, null);
				dlg.add(panel);
				dlg.center();
			}
			
		});
		
		addButton("Изменить расходник", "brit-add-user", new SelectionListener<ButtonEvent>() {
			
			public void componentSelected(ButtonEvent ce) {
				if (selectedMaterial == null) {
					Info.display("Выберите ", "расходный материал");
					return;
				}
				PopupPanel dlg = new PopupPanel();
				dlg.setAnimationEnabled(true);
				dlg.setSize("500px", "300px");
				UsedMaterialForProcedurePanel panel = new UsedMaterialForProcedurePanel(PriceProcedurePanel.this, 
						dlg, (IncomeMaterialsBean)selectedMaterial.getBean());
				dlg.add(panel);
				dlg.center();
			}
			
		});
		
		addButton("Удалить расходник", "brit-delete-user", new SelectionListener<ButtonEvent>() {
			
			public void componentSelected(ButtonEvent ce) {
				if (selectedMaterial == null) {
					Info.display("Выберите ", "расходный материал");
					return;
				}
				deleteMaterial();
			}
		});
		
		grid = new Grid<BeanModel>(store, getColomnModel());
		grid.setStyleAttribute("borderTop", "none");
		grid.setBorders(true);
		grid.setLoadMask(true);
		grid.getView().setForceFit(true);
		GridSelectionModel<BeanModel> sel = grid.getSelectionModel();
		sel.setSelectionMode(Style.SelectionMode.SINGLE);
		
		sel.addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {
					public void handleEvent(
							final SelectionChangedEvent<BeanModel> selEv) {
						setSelectedPrice(selEv.getSelectedItem());
					}
				});
		pricePanel.add(grid);
		add(pricePanel, new RowData(.35, 1));
		
		initMaterialPanel();
	}
	
	private void initMaterialPanel() {
		matGrid = new Grid<BeanModel>(matStore, getMaterialColomnModel());
		matGrid.setStyleAttribute("borderTop", "none");
		matGrid.setBorders(true);
		matGrid.setLoadMask(true);
		matGrid.getView().setForceFit(true);
		GridSelectionModel<BeanModel> sel = matGrid.getSelectionModel();
		sel.setSelectionMode(Style.SelectionMode.SINGLE);
		
		sel.addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {
					public void handleEvent(
							final SelectionChangedEvent<BeanModel> selEv) {
						selectedMaterial = selEv.getSelectedItem();
					}
				});
		priceMaterPanel.add(matGrid);
		add(priceMaterPanel, new RowData(.65, 1));
	}
	
	public void setPrice(List<PriceBean> prices) {
		if (prices == null) {
			store.removeAll();
			return;
		}
		store.removeAll();
		for (PriceBean b : prices) {
    		store.add(priceFactory.createModel(b));
    	}
		setSelectedPrice(null);
		
	}
	
	public void addPrice(PriceBean price) {
		if (price == null) {
			return;
		}
		//store.removeAll();
		//for (PriceBean b : prices) {
    		store.add(priceFactory.createModel(price));
    	//}
		setSelectedPrice(null);
		
	}
	
	public List<PriceBean> getPrice() {
		List<PriceBean> prices = new ArrayList<PriceBean>();
		for (int i = 0; i < store.getCount(); i ++) {
			prices.add((PriceBean)store.getAt(i).getBean());
		}
		return prices;
	}
	
	private void refreshMatStore() {
		matStore.removeAll();
		
        if (materialFactory != null) {
        	for (IncomeMaterialsBean b : ((PriceBean)selectedPriceBean.getBean()).getList()) {
        		matStore.add(materialFactory.createModel(b));
        	}
        }
	}
	
	private void setSelectedPrice(BeanModel model) {
		if (model != null) {
			selectedPriceBean = model;
			refreshMatStore();
		}
		else {
			selectedPriceBean = null;
			matStore.removeAll();
			selectedMaterial = null;
		}	
	}
	
	
	private ColumnModel getColomnModel() {
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

		ColumnConfig conf = new ColumnConfig("name", "Имя услуги", 70);
		configs.add(conf);
		
		conf = new ColumnConfig("cost", "Цена", 70);
		configs.add(conf);
		
		ColumnModel cm = new ColumnModel(configs);
		return cm;
	}
	
	GridCellRenderer<BeanModel> nameRenderer = null;

	public GridCellRenderer<BeanModel> getNameRenderer() {
		if (nameRenderer == null) {
			nameRenderer = new GridCellRenderer<BeanModel>() {

				@Override
				public Object render(BeanModel model, String property,
						ColumnData config, int rowIndex, int colIndex,
						ListStore<BeanModel> store, Grid<BeanModel> grid) {
					IncomeMaterialsBean bean = model.getBean();
					if (bean != null) {
						return bean.getDisplayF();
					}
					return "";
				}
			};
		}
		return nameRenderer;
	}
	
	private ColumnModel getMaterialColomnModel() {
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
		
		ColumnConfig conf = new ColumnConfig("name", "Наименование товара", 150);
		conf.setRenderer(getNameRenderer());
		configs.add(conf);
		
		conf = new ColumnConfig("count", "Количество", 50);
		configs.add(conf);
		
		
		ColumnModel cm = new ColumnModel(configs);
		return cm;
	}
	
	protected void addButton(String title, String icon, SelectionListener<ButtonEvent> listener) {		
		Button button = new Button(title);
		button.addSelectionListener(listener);
		/*if (icon != null) {
			button.setIcon(IconHelper.createStyle(icon));
		}*/
		toolbar.add(button);
	}
	
	public void addMaterial(IncomeMaterialsBean bean) {
		if (bean == null) {
			return;
		}
		((PriceBean) selectedPriceBean.getBean()).getList().add(bean);
		refreshMatStore();
	}
	
	public void editMaterial(IncomeMaterialsBean bean) {
		if (bean == null) {
			return;
		}
		((PriceBean) selectedPriceBean.getBean()).getList().remove(bean);
		((PriceBean) selectedPriceBean.getBean()).getList().add(bean);
		refreshMatStore();
	}
	
	public void deleteMaterial() {
		if (selectedMaterial == null) {
			return;
		}
		((PriceBean) selectedPriceBean.getBean()).getList().remove(selectedMaterial.getBean());
		refreshMatStore();
	}
}